<?php

namespace App\Http\Controllers;

use App\Models\Member;
use Illuminate\Http\Request;

class MemberAuthController extends Controller
{
    //前台用户登录
    public function login(Request $request)
    {
        $Wechat = $this->wechat();
        $Fans = $Wechat->oauth->userFromCode($request->input('code'));
        if(!$Member = Member::where('openid',$Fans->getId())->first()) {
            $Member = Member::create([
                'nickname' => $Fans->getNickname(),
                'avatar' => $Fans->getAvatar(),
                'openid' => $Fans->getId()
            ]);
        }
        $_token = auth('member')->login($Member);
        return $this->respondWithToken($_token);
    }

    /**
     * Get the token array structure.
     *
     * @param  string $token
     *
     * @return \Illuminate\Http\JsonResponse
     */
    protected function respondWithToken($token)
    {
        return response()->json([
            'access_token' => $token,
            'token_type' => 'bearer',
            'expires_in' => auth()->factory()->getTTL() * 60
        ]);
    }
}
